package cn.uniquesoft.controller;

import cn.uniquesoft.controller.base.BaseController;
import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.page.DataGrid;
import cn.uniquesoft.service.ISearchService;
import cn.uniquesoft.service.IVideosService;
import cn.uniquesoft.util.ContextUtil;
import cn.uniquesoft.util.DateUtil;
import cn.uniquesoft.util.UploadUtil;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.SearchVO;
import cn.uniquesoft.vo.UserVO;
import cn.uniquesoft.vo.VideosVO;
import cn.uniquesoft.vo.base.BaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
@Controller
@RequestMapping(value="/videos")
public class VideosController extends BaseController<VideosVO> {
		private IVideosService videosService;
		@Autowired
		private ISearchService searchService;
	private static String videoExts = ".rm,.rmvb,.avi,.mp4,.3gp";//视频格式
	public VideosController(IVideosService videosService){
			super();
			this.baseService=videosService;
			this.videosService=videosService;
			this.indexName="videos/index";
		}

	@RequestMapping(value = "/index1")
	public String index1(Model model) {
		UserVO userVO = null;
		try {
			userVO = ClientManager.getInstance().getClient().getUser();
		} catch (Exception e) {

		}
		model.addAttribute("iusertype", userVO.getIusertype());
		return indexName;
	}

	@RequestMapping(value = "/save1")
	@ResponseBody
	public AnswerVO save1(VideosVO item, HttpServletRequest request) {
				AnswerVO answerVO = new AnswerVO();
		UserVO userVO = null;
		try {
			userVO = ClientManager.getInstance().getClient().getUser();
		} catch (Exception e) {

		}
		if (userVO != null) {
			item.setIorgname(userVO.getIorgname());
			item.setIcreator(userVO.getIid());
			item.setCcreator(userVO.getCname());
			item.setImodify(userVO.getIid());
			item.setCmodify(userVO.getCname());
			Date date = new Date();
			item.setDcreator(date);

			item.setDmodify(date);
		}
		item.setIspassed("2");
				try {
					MultipartFile file = item.getUpfile();
					if(file.getSize()>0){
						String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
						// 获得上传文件原始名
						String oldname = file.getOriginalFilename();
						// 算出后缀名
						String ext = oldname.substring(oldname.lastIndexOf("."));
						// 文件名为：问题名称 + image + UUID + 后缀
						String fileName = "videos" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
						String filepath = "files"+ File.separator + "videos" + File.separator;
						String fileFolder = tomurl+filepath;
						File upload = new File(fileFolder);
						if(!upload.exists()) upload.mkdirs();
						File localFile = new File(fileFolder, fileName);
						// 直接写入到后台服务器，简单且快
						file.transferTo(localFile);
						item.setCcoverimg(filepath+fileName);
						
					}
					MultipartFile file1 = item.getUpfile1();
					if(file1.getSize()>0){
						String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
						// 获得上传文件原始名
						String oldname = file1.getOriginalFilename();
						// 算出后缀名
						String ext = oldname.substring(oldname.lastIndexOf("."));
						if (videoExts.indexOf(ext) == -1) {
							answerVO.setSuccess(false);
							answerVO.setMsg("上传失败,只能上传" + videoExts + "格式的视频！");
							return answerVO;
						}
						// 文件名为：问题名称 + image + UUID + 后缀
						String fileName = "videos" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
						String filepath = "files"+ File.separator + "videos" + File.separator;
						String fileFolder = tomurl+filepath;
						File upload = new File(fileFolder);
						if(!upload.exists()) upload.mkdirs();
						File localFile = new File(fileFolder, fileName);
						// 直接写入到后台服务器，简单且快
						file1.transferTo(localFile);
						item.setCurl(UploadUtil.getFileUrl(request) + filepath + fileName);
						
					}
					this.videosService.save(item);
					int itemId = ((BaseVO) item).getIid();
					if (itemId > 0) {
						SearchVO searchVO = new SearchVO();
						searchVO.setTname("video");
						searchVO.setTid(item.getIid()+"");
						searchVO.setTvalue(item.toString());
						System.out.println(item.toString());
						searchVO.setTtitle(item.getCtitle());
						searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
						this.searchService.save(searchVO);
						answerVO.setSuccess(true);
						answerVO.setMsg("新增成功!");
					} else {
						answerVO.setSuccess(false);
						answerVO.setMsg("新增失败!");
					}
					answerVO.setData(itemId);
				} catch (Exception e) {
					e.printStackTrace();
					answerVO.setSuccess(false);
					answerVO.setMsg("新增失败," + e.getMessage());
				}
				return answerVO;
			}

	@RequestMapping(value = "/edit1")
	@ResponseBody
	public AnswerVO edit1(VideosVO item, HttpServletRequest request) {
		AnswerVO answerVO = new AnswerVO();
		UserVO userVO = null;
		item.setIspassed("2");
		try {
			userVO = ClientManager.getInstance().getClient().getUser();
		} catch (Exception e) {

		}
		if (userVO != null) {
			item.setIorgname(userVO.getIorgname());
			Date date = new Date();
			item.setImodify(userVO.getIid());
			item.setCmodify(userVO.getCname());
			item.setDmodify(date);
		}
		try {
			MultipartFile file = item.getUpfile();
			if(file.getSize()>0){
				File path = new File(ResourceUtils.getURL("classpath:").getPath());
				if(!path.exists()) path = new File("");
				// 获得上传文件原始名
				String oldname = file.getOriginalFilename();
				// 算出后缀名
				String ext = oldname.substring(oldname.lastIndexOf("."));
				// 文件名为：问题名称 + image + UUID + 后缀
				String fileName = "videos" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
				String tomurl = path.getAbsolutePath()+File.separator;
				String filepath = "files"+ File.separator + "videos" + File.separator;
				String fileFolder = tomurl+filepath;
				File upload = new File(fileFolder);
				if(!upload.exists()) upload.mkdirs();
				File localFile = new File(fileFolder, fileName);
				// 直接写入到后台服务器，简单且快
				file.transferTo(localFile);
				item.setCcoverimg(filepath+fileName);

			}
			MultipartFile file1 = item.getUpfile1();
			if(file1.getSize()>0){
				String tomurl = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/");
				// 获得上传文件原始名
				String oldname = file1.getOriginalFilename();
				// 算出后缀名
				String ext = oldname.substring(oldname.lastIndexOf("."));
				if (videoExts.indexOf(ext) == -1) {
					answerVO.setSuccess(false);
					answerVO.setMsg("上传失败,只能上传" + videoExts + "格式的视频！");
					return answerVO;
				}
				// 文件名为：问题名称 + image + UUID + 后缀
				String fileName = "videos" + DateUtil.date2timestamp(new Date(), DateUtil.FORMAT_DATETIME) + ext;
				String filepath = "files"+ File.separator + "videos" + File.separator;
				String fileFolder = tomurl+filepath;
				File upload = new File(fileFolder);
				if(!upload.exists()) upload.mkdirs();
				File localFile = new File(fileFolder, fileName);
				// 直接写入到后台服务器，简单且快
				file1.transferTo(localFile);
				item.setCurl(UploadUtil.getFileUrl(request) + filepath + fileName);

			}
			this.videosService.edit(item);
			int itemId = ((BaseVO) item).getIid();
			if (itemId > 0) {
				this.searchService.remove(item.getIid()+"", "video");
				SearchVO searchVO = new SearchVO();
				searchVO.setTname("video");
				searchVO.setTid(item.getIid()+"");
				searchVO.setTvalue(item.toString());
				System.out.println(item.toString());
				searchVO.setTtitle(item.getCtitle());
				searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
				this.searchService.save(searchVO);
				answerVO.setSuccess(true);
				answerVO.setMsg("新增成功!");
			} else {
				answerVO.setSuccess(false);
				answerVO.setMsg("新增失败!");
			}
			answerVO.setData(itemId);
		} catch (Exception e) {
			e.printStackTrace();
			answerVO.setSuccess(false);
			answerVO.setMsg("新增失败," + e.getMessage());
		}
		return answerVO;
	}
	@RequestMapping(value = "/removeById")
	@ResponseBody
	@Override
	public AnswerVO removeById(int  iid) {
		AnswerVO answerVO = new AnswerVO();
		try {
			int result = this.baseService.removeById(iid);

			if (result > 0) {
				this.searchService.remove(iid+"", "video");
				answerVO.setSuccess(true);
				answerVO.setMsg("删除成功!");
			} else {
				answerVO.setSuccess(false);
				answerVO.setMsg("删除失败!");
			}
			answerVO.setData(result);
		} catch (Exception e) {
			answerVO.setSuccess(false);
			answerVO.setMsg("删除失败," + e.getMessage());
		}

		return answerVO;
	}

	@RequestMapping(value = "/removeByIds")
	@ResponseBody
	@Override
	public AnswerVO removeByIds(String ids) {
		AnswerVO answerVO = new AnswerVO();
		try {
			int result = this.baseService.removeByIds(ids);

			if (result > 0) {
				String[] ss = ids.split(",");
				for(int i=0;i<ss.length;i++){
					this.searchService.remove(ss[i]+"", "video");
				}
				answerVO.setSuccess(true);
				answerVO.setMsg("删除成功!");
			} else {
				answerVO.setSuccess(false);
				answerVO.setMsg("删除失败!");
			}
			answerVO.setData(result);
		} catch (Exception e) {
			answerVO.setSuccess(false);
			answerVO.setMsg("删除失败," + e.getMessage());
		}

		return answerVO;
	}

	@RequestMapping(value = "/shenhe")
	@ResponseBody
	public AnswerVO shenhe(VideosVO item) {
		AnswerVO answerVO = new AnswerVO();
		int result = this.videosService.shnehe(item);
		if (result > 0) {
			answerVO.setSuccess(true);
			answerVO.setMsg("审核成功!");
		} else {
			answerVO.setSuccess(false);
			answerVO.setMsg("审核失败!");
		}
		return answerVO;
	}

	@RequestMapping(value = "/pageQuery")
	@ResponseBody
	public DataGrid pageQuery(VideosVO item) {
		DataGrid dg = new DataGrid();
		UserVO userVO = null;
		try {
			userVO = ClientManager.getInstance().getClient().getUser();
		} catch (Exception e) {

		}
		if (userVO != null) {
			if (userVO.getIvisible() == 1) {

			} else if (userVO.getIvisible() == 2) {
				item.setIorgname(userVO.getIorgname());
			} else {
				item.setIcreator(userVO.getIid());
			}
		}
		return this.baseService.pageQuery(item);
	}
}
